package edu.mse.camel.client.serverlib.internal;

public class QueryThread extends Thread {
	
	// milliseconds between polling
	final long timeBetweenPolling = 200;
	final long minYieldTime = 50;
	
	private volatile boolean shouldContinue = true;
	private volatile boolean pause = true;
	
	private ICamelServerPolling handler;
		
	public QueryThread (ICamelServerPolling handler) {
		this.handler = handler;
		
		// a daemon thread does not stop the Java VM from terminating itself
		this.setDaemon(true);
		
		this.setPriority(MIN_PRIORITY);
	}
	
	public void PollImmediately () {
		//interrupt();
	}
	
	public void run () {
		while(shouldContinue) {
			try {
				boolean pollImmediately = false;
				long t1 = System.currentTimeMillis();
				if (!pause) {
					pollImmediately = handler.poll();
					if(pollImmediately) {
						continue;
					}
				}
				long t2 = System.currentTimeMillis();
				
				if ( t2 < t1 ) {
					t2 = t1;
				}
				
				long timeSpentInPolling = t2-t1;
				
				long timeSleep = 0;
				if ( (t2-t1) <= timeBetweenPolling ) {
					timeSleep = timeBetweenPolling - timeSpentInPolling;
				}
				
				if(timeSleep <= minYieldTime) {
					timeSleep = minYieldTime;
				}
				
				sleep(timeSleep);

			} catch (InterruptedException e) {
				System.out.println("interrupted");
			}
		}
	}

	public void abort() {
		this.shouldContinue = false;
	}
	
	public void pausePolling() {
		this.pause = true;
	}
	
	public void resumePolling() {
		this.pause = false;
	}
}
